var calendarService;
var calendarFeedUri = 'http://www.google.com/calendar/feeds/default/private/full';
var calendarScope = 'http://www.google.com/calendar/feeds/';
var events = new Array();

function setupCalendarService() {
	calendarService = new google.gdata.calendar.CalendarService('team4-collegeMaps-1.0');
}

function allowCalendar() {
	var calendarToken = google.accounts.user.login(calendarScope);
}

function initCalendar() {
	setupCalendarService();
	getMyCalendar();
}

function getMyCalendar() {
	google.accounts.user.getInfo(handleInfo);
	if (google.accounts.user.checkLogin(calendarScope)) {
		var query = new google.gdata.calendar.CalendarEventQuery(calendarFeedUri);
		calendarService.getEventsFeed(query, handleCalendarFeed, handleCalendarError);
	}
}

function handleInfo(data) {
    var response = eval(data.currentTarget.responseText);
  
    alert('Target: ' + response.Target + "\n" + 
          'Scope: ' + response.Scope + "\n" +
          'Secure: ' + response.Secure);
}

var handleCalendarFeed = function(result) {  
	if (google.accounts.user.checkLogin(calendarScope)) {
		var entries = result.feed.entry;	
		var calendarPanel = document.getElementById("calendar");
		var code =  '<ul>';
	  
		for (var i = 0; i < entries.length; i++) {
			var eventEntry = entries[i];
			var eventTitle = eventEntry.getTitle().getText();
			events.push(eventEntry);
			code += "<li>" + eventTitle + "</li>";
		}
		
		code += "</ul>";
		calendarPanel.innerHTML += code;
	}
}

function handleCalendarError(e) {
	alert("An error has occurred with the calendar.\n" + e.cause ? e.cause.statusText : e.message);
}

function makeEvent(latlng) {
	// Create an instance of CalendarEventEntry representing the new event
	var entry = new google.gdata.calendar.CalendarEventEntry();

	// Set the title of the event
	entry.setTitle(google.gdata.Text.create(document.placeEventForm.title.value));

	// Create a When object that will be attached to the event
	var when = new google.gdata.When();

	// Set the start and end time of the When object
	var startTime = google.gdata.DateTime.fromIso8601("2008-02-10T09:00:00.000-08:00");
	var endTime = google.gdata.DateTime.fromIso8601("2008-02-10T10:00:00.000-08:00");
	when.setStartTime(startTime);
	when.setEndTime(endTime);
	
	var where = new google.gdata.Where();
	where.setLabel("latlng" + latlng);
	where.setValueString("latlng" + latlng);
	entry.addLocation(where);

	// Add the When object to the event 
	entry.addTime(when);
	
	coords = latlng.split(",");
	lat = Number(coords[0].slice(1));
	lng = Number(coords[1].slice(0, -1));
	
	// Submit the request using the calendar service object
	calendarService.insertEntry(calendarFeedUri, entry, reloadPage, 
	    handleCalendarError, google.gdata.calendar.CalendarEventEntry);
}
		
function reloadPage() {
	location.href = location.href;
}